package com.zige.zige.bj_vr;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.zige.zige.R;
import com.zige.zige.activity.BaseActivity;
import com.zige.zige.constants.Constants;
import com.zige.zige.constants.UrlConsts;
import com.zige.zige.dialog.PromptDialog;
import com.zige.zige.dialog.ZiGeShareDialog;
import com.zige.zige.pojo.UserInfo;
import com.zige.zige.pojo.VideoInfo;
import com.zige.zige.task.PostRequestTask;
import com.zige.zige.task.TaskExecutor;
import com.zige.zige.utils.PreferencesUtils;
import com.zige.zige.utils.SharedPreferencesUtils;
import com.zige.zige.utils.StringUtils;
import com.zige.zige.utils.SystemUtils;
import com.zige.zige.utils.ToastUtils;
import com.zige.zige.view.MyImageTextButten;
import com.zige.zige.view.panoplayer.PanoPlayerView;
import com.zige.zige.view.panoplayer.VideoStateListener;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;


/**
 * Created by admin on 16/1/5.
 */
public class BJVrVideoDetailActivity extends BaseActivity implements View.OnClickListener {

    private ArrayList<VideoInfo> playList;
    int currentPosition = 0;
    private int operate;
    private String  vid;

    private String isPraises, jxVideoId;
    private String mVideoUrl;
    private String videoTitle, videoContext, videoImageUrl;

    private ImageButton mBtnPlay;
    private ImageButton mBtnPause;
    private Button mBtnControlMode;
    private Button mBtnDisplayMode;
    private Button mBtnFullscreen;
    private SeekBar mSeekBar;
    private PanoPlayerView mPanoView;

    private LinearLayout lay_title;
    private TextView tv_title;
    private ImageView vrplay_back;
    private UserInfo userInfo;

    private TextView videoTitleTv, publisherTv, videoContextTv;
    private MyImageTextButten zanBtn, shareBtn, tuijianBtn;
    private boolean isControlMode =true;
    private boolean isDisplayMode =true;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
        setContentView(R.layout.activity_bj_vrvideo_details);
        userInfo = application.getUserInfo();
        initView();

        alert = new AlertDialog.Builder(this);
        MyAsync myAsync = new MyAsync();
        myAsync.execute(getIntent());


    }

    private void initView() {
        mPanoView = (PanoPlayerView)findViewById(R.id.pano_view);
        mBtnPlay = (ImageButton)findViewById(R.id.btn_play);
        mBtnPause = (ImageButton)findViewById(R.id.btn_pause);
        mBtnControlMode = (Button)findViewById(R.id.btn_control_mode);
        mBtnDisplayMode = (Button)findViewById(R.id.btn_display_mode);
        mBtnFullscreen = (Button) findViewById(R.id.btn_fullscreen);
        mSeekBar = (SeekBar)findViewById(R.id.seek_bar);

        tv_title = serchViewById(R.id.title_name);
        tv_title.setText("视频详情");
        vrplay_back = serchViewById(R.id.image_back);
        vrplay_back.setOnClickListener(this);

        videoTitleTv = serchViewById(R.id.video_title);
        publisherTv = serchViewById(R.id.publisher);
        videoContextTv = serchViewById(R.id.video_context);

        shareBtn = findViewByIds(R.id.share_btn);
        shareBtn.setImage(R.drawable.share);
        shareBtn.setText("分享");
        shareBtn.setOnClickListener(this);
        tuijianBtn = findViewByIds(R.id.tuijian_btn);
        tuijianBtn.setText("我要推荐");
        tuijianBtn.setImage(R.drawable.tuijian);
        tuijianBtn.setOnClickListener(this);

        /***点赞*/
        zanBtn = findViewByIds(R.id.zan_btn);
        zanBtn.setImage(R.drawable.zan);
        zanBtn.setText("赞");
        zanBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (application.isLogin()) {

                    setPressPraise(operate);


                } else {
                    PromptDialog dialog = new PromptDialog();
                    dialog.show(getFragmentManager(), "dialo");
                }

            }
        });

        lay_title = serchViewById(R.id.lay_title);

        mBtnPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null == mPanoView) return;
                mPanoView.getVideoPlayer().play();
                mBtnPlay.setVisibility(View.GONE);
                mBtnPause.setVisibility(View.VISIBLE);

            }
        });

        mBtnPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null == mPanoView) return;
                mPanoView.getVideoPlayer().pause();
                mBtnPause.setVisibility(View.GONE);
                mBtnPlay.setVisibility(View.VISIBLE);
            }
        });

        mBtnControlMode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isControlMode){
                    mBtnControlMode.setBackgroundResource(R.drawable.tuoluoyi);
                    mPanoView.setGyroControlEnabled(isControlMode);
                }else {

                    mPanoView.setGyroControlEnabled(isControlMode);
                    mBtnControlMode.setBackgroundResource(R.drawable.tuoluoyi_select);
                }
                isControlMode = !isControlMode;

            }
        });
        mBtnDisplayMode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isDisplayMode){
                    mBtnDisplayMode.setBackgroundResource(R.drawable.btn_vr_on);
                    mPanoView.setVrModeEnabled(isDisplayMode);

                }else {
                    mBtnDisplayMode.setBackgroundResource(R.drawable.btn_vr_off);
                    mPanoView.setVrModeEnabled(isDisplayMode);
                }
                isDisplayMode = !isDisplayMode;
            }
        });

        mBtnFullscreen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    mPanoView.getVideoPlayer().seekToPercentage(progress / 100.0);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                mPanoView.getVideoPlayer().beforeSeek();
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mPanoView.getVideoPlayer().seekToPercentage(seekBar.getProgress() / 100.0);
                mPanoView.getVideoPlayer().afterSeek();
            }
        });

        mPanoView.getVideoPlayer().setVideoStateListener(new myVideoStateListener());
    }


    private void play(String videoUrl,String vid) {
//		String url = video.getDefult().getPlayUrl();
        if (application.isLogin()) {
            userWatchRecord(vid);
        }
        if (StringUtils.isEmpty(videoUrl)) {
            ToastUtils.showToast(this, "视频链接不可用");
            return;
        }
        mPanoView.getVideoPlayer().prepare(videoUrl);
       videoPlay();


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.image_back:
                finish();
                break;
            case R.id.tuijian_btn:

                break;
            case R.id.share_btn:
                pausePlay();
                sharesina();
                break;

        }
    }

    class myVideoStateListener implements VideoStateListener{
        @Override
        public void onPrepared(boolean succeed) {
            if (succeed) {
                mBtnPlay.setEnabled(true);
            }
            mPanoView.getVideoPlayer();
        }

        @Override
        public void onStarted() {
//            mBtnPlay.setVisibility(View.GONE);
//            mBtnPause.setVisibility(View.VISIBLE);
        }

        @Override
        public void onPaused(boolean needBuffer) {
//            mBtnPause.setVisibility(View.GONE);
//            mBtnPlay.setVisibility(View.VISIBLE);
        }

        @Override
        public void onResumed() {
//            mBtnPlay.setVisibility(View.GONE);
//            mBtnPause.setVisibility(View.VISIBLE);
        }

        @Override
        public void onProgress(float currentPercentge, float loadedPercentage) {
            mSeekBar.setProgress((int) (currentPercentge * 100));
            mSeekBar.setSecondaryProgress((int) (loadedPercentage * 100));
        }

        @Override
        public void onStopped() {
//            mBtnPause.setVisibility(View.GONE);
//            mBtnPlay.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

    }





    private void videoPlay(){
        mPanoView.getVideoPlayer().play();
        mBtnPlay.setVisibility(View.GONE);
        mBtnPause.setVisibility(View.VISIBLE);
    }

    private void pausePlay(){
        mPanoView.getVideoPlayer().pause();
        mBtnPause.setVisibility(View.GONE);
        mBtnPlay.setVisibility(View.VISIBLE);
    }


    private void getVideoDetils(String videoId) {
        HashMap<String, String> params = new HashMap<>();
        params.put("vid", videoId);
        showLoadingDialog();
        TaskExecutor.getInstance().execute(new PostRequestTask(params, BJVrVideoDetailActivity.this, UrlConsts.VIDEO_DETILS) {
            @Override
            protected void handleResponse(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    int ret = object.getInt("code");
                    String msg = object.getString("message");
                    if (ret == 0000) {
                        closeLoadingDialog();
                        object = object.getJSONObject("jxVideo");
                        jxVideoId = object.getString("id");
                        videoTitle = object.getString("videoName");
                        videoTitleTv.setText(videoTitle);
                        publisherTv.setText("推荐人：" + object.getString("referrer"));
                        mVideoUrl = object.getString("videoUrl");
                        videoContext = object.getString("videoDesc");
                        videoContextTv.setText(videoContext);
                        videoImageUrl = object.getString("videoPicUrl");
                        isPraises = object.getString("praiseUserids");
                        play(mVideoUrl,jxVideoId);
                        if (application.isLogin()) {
                            if (isPraises.contains(userInfo.userID)) {
                                zanBtn.setImage(R.drawable.zan_selected);
                                operate = 1;
                            } else {
                                zanBtn.setImage(R.drawable.zan_normal);
                                operate = 0;
                            }
                        } else {
                            zanBtn.setImage(R.drawable.zan_normal);
                        }
                    } else {
                        throw new Exception(msg);
                    }
                } catch (Exception e) {
//                    ToastUtils.showToast(VideoDetialsActivity.this, e.getMessage());
//                    tv_check_error.setVisibility(View.VISIBLE);
                    closeLoadingDialog();
                } finally {
                    closeLoadingDialog();
                }
            }

            @Override
            protected void handleError() {
                super.handleError();
            }
        });
    }

    /***
     * 点赞
     *
     * @param operated
     */
    private void setPressPraise(final int operated) {
        String deviceId = SystemUtils.getDeviceKey(BJVrVideoDetailActivity.this);
        HashMap<String, String> params = new HashMap<>();
        params.put("deviceId", deviceId);
        params.put("uid", userInfo.userID);
        params.put("account", userInfo.phoneNumber);
        params.put("jxVideoId", jxVideoId);
        params.put("operate", String.valueOf(operated));
        showLoadingDialog();
        TaskExecutor.getInstance().execute(new PostRequestTask(params, BJVrVideoDetailActivity.this, UrlConsts.VIDEO_PRAISE) {
            @Override
            protected void handleResponse(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    int ret = object.getInt("code");
                    String msg = object.getString("message");
                    if (ret == 0000) {
                        closeLoadingDialog();
                        if (application.isLogin()) {
                            if (isPraises.contains(userInfo.userID)) {
                                zanBtn.setImage(R.drawable.zan_selected);
                                operate = 1;
                            } else {
                                zanBtn.setImage(R.drawable.zan_normal);
                                operate = 0;
                            }
                        } else {
                            zanBtn.setImage(R.drawable.zan_normal);

                        }
                    } else {
                        closeLoadingDialog();
                        throw new Exception(msg);
                    }
                } catch (Exception e) {
                    ToastUtils.showToast(BJVrVideoDetailActivity.this, e.getMessage());
//                    tv_check_error.setVisibility(View.VISIBLE);
                } finally {
                    closeLoadingDialog();
                }
            }
        });
    }



    class MyAsync extends AsyncTask<Intent, Integer, String> {

        @Override
        protected String doInBackground(Intent... params) {
            Intent intent = params[0];
            playList = (ArrayList<VideoInfo>) intent.getSerializableExtra("playList");
            currentPosition = intent.getIntExtra("position", 0);
            if (playList == null || playList.size() < 1) {
                ToastUtils.showToast(BJVrVideoDetailActivity.this, "无视频数据");
                finish();
            }
            registerReceiver();
            publishProgress(100);
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            if (100 == values[0])
                getVideoDetils(playList.get(currentPosition).getId());
            super.onProgressUpdate(values);
        }

    }

    //向服务器发送已登录用户观看记录
    private void userWatchRecord(String videoId) {
        HashMap<String, String> params = new HashMap<>();
        params.put("uid", application.getUserInfo().userID);
        params.put("videoId", videoId);
        TaskExecutor.getInstance().execute(new PostRequestTask(params, BJVrVideoDetailActivity.this, UrlConsts.USER_WATCH_RECORD) {
            @Override
            protected void handleResponse(String response) {

            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        pausePlay();
        unregisterReceiver();
    }

    NetworkStateChangedReceiver myReceiver;

    private void registerReceiver() {
        boolean isWifiOnly = PreferencesUtils.getBoolean(this, Constants.PREFERENCE_KEY_IS_WIFI_ONLY);
        boolean on =  (boolean) SharedPreferencesUtils.getValue(this, SharedPreferencesUtils.gesture_toggle, false);
        if(on || isWifiOnly){
            return;
        }
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        myReceiver = new NetworkStateChangedReceiver();
        this.registerReceiver(myReceiver, filter);
    }

    private void unregisterReceiver() {
        if (myReceiver != null) {
            this.unregisterReceiver(myReceiver);
            myReceiver = null;
        }
    }

    AlertDialog.Builder alert;
    class NetworkStateChangedReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager connectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mobNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            NetworkInfo wifiNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

            if (!mobNetInfo.isConnected() && !wifiNetInfo.isConnected()) {
                ToastUtils.showToast(context, "网络不可以用");
                // 改变背景或者 处理网络的全局变量
            } else if (!wifiNetInfo.isConnected()) {
               pausePlay();
                AlertDialog.Builder alert = new AlertDialog.Builder(context);
                alert.setCancelable(false);
                alert.setTitle("提示");
                alert.setMessage("您正在使用非WIFI网络，播放将产生流量费用");
                alert.setPositiveButton("继续播放", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                       videoPlay();
                    }
                }).setNegativeButton("返回", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        pausePlay();
                        finish();
                    }
                }).show();
            }

        }

    }

    private UMImage shareVideoImageUrl;
    private String shareVideoUrl;
    private void sharesina() {
        ZiGeShareDialog dialog = new ZiGeShareDialog();
        dialog.setSharelister(zigeshareLister);
        dialog.show(getFragmentManager(), "dialog");

        if (TextUtils.isEmpty(videoTitle)) {
            videoTitle = "VR小伴马";
        }

        shareVideoUrl = UrlConsts.SHARE_VIDEIO_URL + jxVideoId;
        shareVideoImageUrl = new UMImage(BJVrVideoDetailActivity.this, videoImageUrl);
    }

    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA platform) {
            com.umeng.socialize.utils.Log.d("plat", "platform" + platform);
            Toast.makeText(BJVrVideoDetailActivity.this, platform + " 分享成功啦", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(BJVrVideoDetailActivity.this,platform + " 分享失败啦", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(BJVrVideoDetailActivity.this,platform + " 分享取消了", Toast.LENGTH_SHORT).show();
        }
    };


    private ZiGeShareDialog.ZigeshareLister zigeshareLister = new ZiGeShareDialog.ZigeshareLister() {
        @Override
        public void shareSina() {
            new ShareAction(BJVrVideoDetailActivity.this).setPlatform(SHARE_MEDIA.SINA).setCallback(umShareListener)
                    .withTitle(videoTitle)
                    .withText("分享给大家一个好看的视频：")
                    .withMedia(shareVideoImageUrl)
                    .withTargetUrl(shareVideoUrl)
                    .share();
        }

        @Override
        public void shareWeiXin() {
            new ShareAction(BJVrVideoDetailActivity.this).setPlatform(SHARE_MEDIA.WEIXIN).setCallback(umShareListener)
                    .withTitle(videoTitle)
                    .withText("分享给大家一个好看的视频：")
                    .withMedia(shareVideoImageUrl)
                    .withTargetUrl(shareVideoUrl)
                    .share();
        }

        @Override
        public void shareWeiXinCircle() {
            new ShareAction(BJVrVideoDetailActivity.this).setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE).setCallback(umShareListener)
                    .withTitle(videoTitle)
                    .withText("分享给大家一个好看的视频：")
                    .withMedia(shareVideoImageUrl)
                    .withTargetUrl(shareVideoUrl)
                    .share();
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /** attention to this below ,must add this**/
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }
}
